package cn.luoyifan.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//把这个类交给spring管理
@Component
public class PreDecorationFilter extends ZuulFilter{

    //前置Filter
    @Override
    public String filterType() {
        return "pre";
    }

    //执行顺序
    @Override
    public int filterOrder() {
        return 0;
    }

    //返回结果决定是否执行run方法
    @Override
    public boolean shouldFilter() {
        //返回值决定了是否要执行run方法
        //判断请求的URL，如果是login；register，
        //就返回false，不执行run方法因为不需要做登录检查
        //1.获取请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //2.获取请求的URL
        String requestURI = request.getRequestURI();
        //3.判断是否要排除
        if (requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        return true;
    }

    //登录检查，如果请求头中有token，就登录成功
    @Override
    public Object run()throws ZuulException{
        //核心方法，做登录检查
        //1.拿到请求对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //2.拿到请求头中的Token
        String token = request.getHeader("token");
        //判断token是否为空
        if (StringUtils.isEmpty(token)){
            //3.1返回一个请登录错误提示
            HttpServletResponse response = currentContext.getResponse();
            try {
                response.setContentType("application/json;charset-utf-8");
                response.getWriter().write("请登录");
            } catch (Exception e) {
                e.printStackTrace();
            }
            //3.2阻止继续往后执行
            currentContext.setSendZuulResponse(false);
        }
        return null;
    }
}
